using System;
using System.Diagnostics;
using System.Reflection;

namespace ICSharpCode.TextEditor.Utils
{
	[DebuggerNonUserCode]
	public sealed class WeakEventHandler<TEventArgs> where TEventArgs : EventArgs
	{
		private readonly WeakReference _targetReference;

		private readonly MethodInfo _method;

		public WeakEventHandler(EventHandler<TEventArgs> callback)
		{
			this._method = callback.Method;
			this._targetReference = new WeakReference(callback.Target, trackResurrection: true);
		}

		[DebuggerNonUserCode]
		public void Handler(object sender, TEventArgs e)
		{
			object target = this._targetReference.Target;
			if (target != null)
			{
				((Action<object, TEventArgs>)Delegate.CreateDelegate(typeof(Action<object, TEventArgs>), target, this._method, throwOnBindFailure: true))?.Invoke(sender, e);
			}
		}
	}
}
